# -*- coding: utf-8 -*-
'''
Created on 19.08.2019

@author: yu03
'''

import matplotlib.pyplot as plt
import numpy as np
import datetime
from RigolScope_DS4054 import RigolScope
from PyUeye import flash_name


def Export_Data(file_name, header, out_str):
    print('Writing Data')
    with open(file_name,'w') as fid: ######################################################################################
        fid.writelines(header)
        fid.writelines(out_str)
    print('Finish Writing')
    return

def Read_Data_2Ch(name):
    '''
        Return Data in File (4 Channels: Data_Ch1, Data_Ch2, Data_Ch3, Data_Ch4)
        File name required (default path)
    '''
    print('Reading Data')
    with open(name,'r') as fid:
        line=''
        while line[0:4] != '----':
            line = fid.readline()
            print(line)
            if line[0:2] == 'Fs':
                p, q, m, n = line.strip().split(' ')
                Fs = float(m)
                print('Fs = %f\n'%Fs)
        out_str = fid.readlines()
    Data_Ch1, Data_Ch2 = [], []
    for line in out_str:
        a, b= line.strip().split(', ')
        Data_Ch1.append(float(a))
        Data_Ch2.append(float(b))
    Data_Ch1 = np.array(Data_Ch1)
    Data_Ch2 = np.array(Data_Ch2)
    return Data_Ch1, Data_Ch2, Fs



file_name = flash_name


if 1:
    '''
        Read from Oscilloscope
    '''
    now = datetime.datetime.now()
    scope = RigolScope.RigolScope('USB0::0x1AB1::0x04B1::DS4A140800046::INSTR')
    print(scope.Read_ID())
    print(scope.Read_Memory_Depth())
    
    Data_Ch1, Data_Ch2, Memory_Depth, Fs = scope.Read()
    Data = Data_Ch1
    N_Data, tau0= len(Data), 1.0/Fs  # 采样点数,采样间隔
    T = N_Data*tau0 # 采样时间
    timeline = np.array([x*tau0 for x in range(N_Data)]) #采样序列
      
    print('Sample Rate: %e'%Fs)
    print('Memory Depth: %i'%Memory_Depth)
    print('Data Length: %i'%N_Data)
      
      
    ''' 
        输出数据 to TXT
    '''
    header = ['%s\n' %file_name,
          'Local current time : %s\n' %now.strftime("%Y-%m-%d %H:%M:%S"),
          'Fs = %e (Hz)\n' %Fs,##########################################################################################################
          'Data Length: %i\n' %N_Data,############################################################################################
          'Time Scale = %e (s)\n' %T,############################################################################################
          'Channel_1: Trigger\n',############################################################################################
          'Channel_2: Flash\n',############################################################################################
          'Channel_3: XXX\n',############################################################################################
          'Channel_4: XXX\n',############################################################################################
    #       'Channel_3: Demodulated S_curve (from CH_No.2)\n',############################################################################################
    #       'Channel_4: Demodulated S_curve (from CH_No.1)\n',############################################################################################
    #       'Data_Ch5: Difference between Channel_3 & Channel_4 (Ch3-Ch4)\n'################################################################################
          '-------------------------------------------------\n',
          ]
    # out_str = ['%.4f, %.4f, %.4f, %.4f\n' %(Data_Ch1[i], Data_Ch2[i], Data_Ch3[i], Data_Ch4[i]) for i in range(len(Data))] 
    # out_str = [' %.4f, %.4f, %.4f, %.4f, %.4f\n' %(Data_Ch1[i], Data_Ch2[i], Data_Ch3[i], Data_Ch4[i], Data_Ch5[i]) for i in range(len(Data))]    
    out_str = ['%.4f, %.4f\n' %(Data_Ch1[i], Data_Ch2[i]) for i in range(len(Data))]    
      
    ''' 
        保存文件
    '''
    Export_Data(file_name, header, out_str)
      
      
    '''
        Plotting
    '''
    plt.figure(1)   
    plt.plot(Data_Ch1, color='yellow')
    plt.plot(Data_Ch2, color='cyan')

    plt.xlabel('Time [s]')
    plt.ylabel('Voltage [V]')
    plt.grid(which = 'both')
      
    plt.show()




 
if 1: 
    '''
        读取数据 from TXT
    '''
    file_name = flash_name
    now = datetime.datetime.now()
    Data_Ch1, Data_Ch2, Fs = Read_Data_2Ch(file_name)
     
    Data = Data_Ch1
    N_Data = len(Data)
    tau0 = 1/Fs
    T = N_Data*tau0
    print('Sampling Rate: %e'%Fs)
    print('Read length: %i'%N_Data)
     
    # Data_Ch1 = running_mean(Data_Ch1, 100)
    # Data_Ch2 = running_mean(Data_Ch2, 100)
    cutting_start = np.where(np.diff(Data_Ch2)>3)[0][1] + 2
    cutting_end = np.where(np.diff(Data_Ch2)>3)[0][-1] + 2
    print(cutting_start, cutting_end)
     
     
    Trigger = Data_Ch1[cutting_start:cutting_end]
    Flash = Data_Ch2[cutting_start:cutting_end]
     
    Trigger_set = np.where(np.diff(Trigger) > 4)[0]
    Flash_set = np.where(np.diff(Flash) > 2)[0]
     
    Trigger_set = Trigger_set[:6871]
    Flash_set = Flash_set[:6871]
     
    print(len(Trigger_set))
    print(len(Flash_set))
    error = Trigger_set-Flash_set
    print(error)
     
     
    '''
        可视化
    '''
    if 1:
        plt.figure(1)
        plt.subplot(5,1,1)
        plt.plot(Data_Ch1, label='Trigger', color='yellow')
        plt.plot(Data_Ch2, label='Flash', color='cyan')
        plt.grid(which='both', axis='both')
        plt.legend(loc='upper right')
    #     plt.get_current_fig_manager().window.setGeometry(20, 50, 1000, 800)
    #     plt.gca().tick_params(axis='x',labelbottom=False)
         
        plt.subplot(5,1,2)
        plt.plot(Trigger, label='Trigger', color='yellow')
        plt.plot(Flash, label='Flash', color='cyan')
        plt.grid(which='both', axis='both')
        plt.legend(loc='upper right')
         
        plt.subplot(5,1,3)
        plt.plot(np.diff(Trigger), label='Trigger', color='yellow')
        plt.plot(np.diff(Flash), label='Flash', color='cyan')
        plt.grid(which='both', axis='both')
        plt.legend(loc='upper right')
         
        plt.subplot(5,1,4)
        plt.plot(np.diff(Trigger_set), label='Trigger interval', color='yellow')
        plt.plot(np.diff(Flash_set), label='Flash interval', color='cyan')
        plt.grid(which='both', axis='both')
        plt.legend(loc='upper right')
         
        plt.subplot(5,1,5)
        plt.plot(error, label='error', color='red')
        plt.grid(which='both', axis='both')
        plt.legend(loc='upper right')
         
        plt.tight_layout()
        plt.show()
        
        
if 0:
    '''
        Set the Oscilloscope trigger in single mode
    '''
    
    now = datetime.datetime.now()
    scope = RigolScope.RigolScope('USB0::0x1AB1::0x04B1::DS4A140800046::INSTR')
    print(scope.Read_ID())
    scope.Write_Single()
    print('Single Mode')